
package com.ceair.mub2c.payment.payments.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ceair.flight.logging.core.KafkaLayout;
import com.ceair.flight.logging.enums.Source;
import com.ceair.flight.muibeclient.facade.dto.CabinInfoDto;
import com.ceair.flight.muibeclient.facade.dto.FlightInfoDto;
import com.ceair.flight.muibeclient.facade.dto.FlightItem;
import com.ceair.flight.payment.dto.AsyncPaymentCallbackDto;
import com.ceair.flight.payment.dto.CardInfoDto;
import com.ceair.flight.payment.dto.PayResponseDto;
import com.ceair.flight.payment.dto.SyncPaymentCallbackDto;
import com.ceair.flight.payment.service.IPaymentService;
import com.ceair.flight.query.dto.EMDOrderDto;
import com.ceair.flight.query.dto.FlightOrderDto;
import com.ceair.flight.query.dto.PaxDto;
import com.ceair.flight.query.dto.PayDto;
import com.ceair.flight.query.dto.PayProductDto;
import com.ceair.flight.query.dto.SegmentDto;
import com.ceair.flight.query.payment.service.IPayQueryService;
import com.ceair.flight.query.service.IFlightOrderService;
import com.ceair.flight.query.service.IOrderService;
import com.ceair.flight.shopping.service.IFlightCollectService;
import com.ceair.flight.ticket.service.ITicketService;
import com.ceair.mub2c.common.utils.GlobalExceptionConstants;
import com.ceair.mub2c.exceptionhandler.ActionException;
import com.ceair.mub2c.payment.payments.service.PaymentDubboService;
import com.ceair.unified.businessobject.rqrs.unicfg.UniChannelRS;
import com.ceair.unified.ws.unicfgmanager.IUniConfigManagerWS;
import com.google.gson.Gson;

@Source(name="10031010")
@Service
public class PaymentDubboServiceImpl implements PaymentDubboService {
	
	Logger log = Logger.getLogger(getClass());
	
	@Autowired
	private IPaymentService paymentService;
	
	@Autowired
	private IUniConfigManagerWS uniConfigManagerWS;
	
	@Autowired
	private IFlightOrderService flightOrderService;
	
	@Autowired
	private IPayQueryService payQueryService;
	
	@Autowired
	private IFlightCollectService flightCollectServiceImpl;
	
	@Autowired
	private ITicketService ticketService;
	
//	@Autowired
//	private IImportantFlightService importantFlightServiceImpl;
	
//	@Autowired
//	private ICommonCardInfoService commonCardInfoService;
	
	@Autowired
    private IOrderService orderServiceImpl;
	
	@Source(name="100310101003")
	@Override
	public AsyncPaymentCallbackDto asyncPaymentCallback(String charset, PayResponseDto payResp) {
		try {
			log.info(KafkaLayout.format(null, null, null, null, null, "统一支付异步回调，回调service方法paymentService.doAsyncPaymentCallback开始，开始时间：" + System.currentTimeMillis()));
			log.info("调用支付异步回调asyncPaymentCallback参数为：charset="+charset+ ",payResp="+new Gson().toJson(payResp));	
			AsyncPaymentCallbackDto callBackDto = paymentService.doAsyncPaymentCallback(charset, payResp);
			log.info("调用支付异步回调asyncPaymentCallback返回结果为：callBackDto="+new Gson().toJson(callBackDto));
			log.info(KafkaLayout.format(null, null, null, null, null, "统一支付异步回调，回调service方法paymentService.doAsyncPaymentCallback结束，结束时间：" + System.currentTimeMillis()));
			return callBackDto;
		} catch (Exception e) {
			log.error("统一支付异步回调，回调service方法paymentService.doAsyncPaymentCallback异常，结束时间："+ System.currentTimeMillis(),e);
			throw new ActionException(GlobalExceptionConstants.GLOBAL_SERVICE_EXCEPTION_CODE);
		}
	}
	
	@Source(name="100310101002")
	@Override
	public SyncPaymentCallbackDto syncPaymentCallback(String charset, PayResponseDto payResp) {
		try {
			log.info(KafkaLayout.format(null, null, null, null, null, "统一支付同步回调，回调service方法paymentService.doSyncPaymentCallback开始，开始时间：" + System.currentTimeMillis()));
			log.info("调用支付异步回调syncPaymentCallback参数为：charset="+charset+ ",payResp="+new Gson().toJson(payResp));	
			SyncPaymentCallbackDto paySyncDto = paymentService.doSyncPaymentCallback(charset, payResp);
			log.info("调用支付异步回调syncPaymentCallback返回结果为：paySyncDto="+new Gson().toJson(paySyncDto));
			log.info(KafkaLayout.format(null, null, null, null, null, "统一支付同步回调，回调service方法paymentService.doSyncPaymentCallback结束，结束时间：" + System.currentTimeMillis()));
			return paySyncDto;
		} catch (Exception e) {
			log.error("统一支付同步回调，回调service方法paymentService.doSyncPaymentCallback异常，结束时间：" + System.currentTimeMillis(),e);
			throw new ActionException(GlobalExceptionConstants.GLOBAL_SERVICE_EXCEPTION_CODE);
		}
	}
	
	@Source(name="100310101001")
	@Override
	public Map<String, String> paymentSubmit(Integer[] productTypes, String orderNo, String[] productId, Integer payTp, String bankCode, Integer orderTp, String accountInfo, BigDecimal amount, BigDecimal pointAmount, String userId, String userName, String channelCode, String clientIP, CardInfoDto cardInfo, String SCCode, String SubSCCode, String PCCode, String SubPCCode, String PCCodePoint, String SubPCCodePoint, String sessionId,String asyncUrl,String syncUrl, String transWebCountryCode) {
		try {
			log.info(KafkaLayout.format(orderNo, channelCode, userId, userName, clientIP, "支付调用service方法paymentService.paymentSubmitInterface开始，开始时间：" + System.currentTimeMillis()));
			log.info("调用支付提交dubbo服务支付提交paymentSubmitInterface参数为: orderNo="+orderNo + ",productId="+Arrays.deepToString(productId)+ ",productTypes="+Arrays.deepToString(productTypes)+ ",payTp="+ payTp+ ",bankCode="+ bankCode+ ",orderTp="+orderTp+ ",accountInfo="+ accountInfo+ ",amount="+ amount+ ",pointAmount="+ pointAmount
					+ ",userId="+userId+ ",userName="+ userName+ ",channelCode="+channelCode+",clientIP="+ clientIP+",SCCode="+ SCCode+",SubSCCode="+ SubSCCode+",PCCode="+  PCCode+",SubPCCode="+  SubPCCode
					+",PCCodePoint="+ PCCodePoint+",SubPCCodePoint="+  SubPCCodePoint
					+",sessionId="+ sessionId+",asyncUrl="+ asyncUrl+",syncUrl="+ syncUrl+",transWebCountryCode="+ transWebCountryCode);
			Map<String, String> parmeters = paymentService.paymentSubmitInterface(orderNo, productId, productTypes, payTp, bankCode, orderTp, accountInfo, amount, pointAmount, userId, userName, channelCode, clientIP, cardInfo, SCCode, SubSCCode, PCCode, SubPCCode, PCCodePoint, SubPCCodePoint, sessionId, asyncUrl, syncUrl, transWebCountryCode);
			log.info("调用支付提交dubbo服务支付提交paymentSubmitInterface返回结果为="+parmeters);
			log.info(KafkaLayout.format(orderNo, channelCode, userId, userName, clientIP, "支付调用service方法paymentService.paymentSubmitInterface结束，结束时间：" + System.currentTimeMillis()));
			return parmeters;
		} catch (Exception e) {
			log.error("支付调用service方法paymentService.paymentSubmitInterface异常，结束时间：" + System.currentTimeMillis(),e);
			throw new ActionException(GlobalExceptionConstants.GLOBAL_SERVICE_EXCEPTION_CODE);
		}
	}
	
	public Long getChannelCode(String site) {
		UniChannelRS rs = uniConfigManagerWS.findUniChannelBySite(site);
		if (rs.getMsgCode() != 0) return null;
		return rs.getChannel();
	}

	@Source(name="100310101004")
	@Override
	public List<FlightOrderDto> getFlightOrderList(String orderNO) {
		try {
			log.info(KafkaLayout.format(orderNO, null, null, null, null, "统一支付获取机票订单信息调用service方法flightOrderService.getFlightOrderDetailList开始，开始时间：" + System.currentTimeMillis()));
			List<FlightOrderDto> flightList = flightOrderService.getFlightOrderDetailList(orderNO);//统一支付传的是flightOrderNo
			log.info(KafkaLayout.format(orderNO, null, null, null, null, "统一支付获取机票订单信息调用service方法flightOrderService.getFlightOrderDetailList结束，结束时间：" + System.currentTimeMillis()));
			return flightList;
		} catch (Exception e) {
			log.error("统一支付获取机票订单信息调用service方法flightOrderService.getFlightOrderDetailList异常，结束时间：" + System.currentTimeMillis(),e);
			throw new ActionException(GlobalExceptionConstants.GLOBAL_SERVICE_EXCEPTION_CODE);
		}
	}
	
	@Override
	public List<EMDOrderDto> getEmdOrder(String emdOrderNO) {
		try {
			log.info(KafkaLayout.format(emdOrderNO, null, null, null, null, "统一支付获取emd订单信息调用service方法orderServiceImpl.getEmdorder开始，开始时间：" + System.currentTimeMillis()));
			List<String> emdOrderIdList = new ArrayList<String>();
			emdOrderIdList.add(emdOrderNO);
			HashMap<String, Object> paramMap = new HashMap<String, Object>();
	        paramMap.put("emdOrderNoList", emdOrderIdList);
			List<EMDOrderDto> emdOrderDtoList = orderServiceImpl.getEmdorder(paramMap);
			log.info(KafkaLayout.format(emdOrderNO, null, null, null, null, "统一支付获取emd订单信息调用service方法orderServiceImpl.getEmdorder结束，结束时间：" + System.currentTimeMillis()));
			return emdOrderDtoList;
		} catch (Exception e) {
			log.error("统一支付获取机票订单信息调用service方法orderServiceImpl.getEmdorder异常，结束时间：" + System.currentTimeMillis(),e);
			throw new ActionException(GlobalExceptionConstants.GLOBAL_SERVICE_EXCEPTION_CODE);
		}
	}

	@Override
	public List<PayDto> getPayStatus(String orderNo, String[] emdOrderNos,
			String flightOrderNo) {
		PayProductDto payProductDto = new PayProductDto();
		if(emdOrderNos==null && StringUtils.isEmpty(flightOrderNo)){
			//只传大订单号，支付新生成飞机订单
			payProductDto.setOrderNo(orderNo);
		}else if(emdOrderNos!=null){
			//支付emd选座订单
			Arrays.sort(emdOrderNos);
			String orderProductIds=orderNo+Arrays.deepToString(emdOrderNos).replaceAll(" ", "");
			payProductDto.setOrderProductIds(orderProductIds);
		}else if(!StringUtils.isEmpty(flightOrderNo)) {
			//支付改期飞机订单
			String orderProductId = orderNo+"["+flightOrderNo+"]";
			payProductDto.setOrderProductIds(orderProductId);
		}
		log.info("调用服务层方法开始");
		List<PayDto> payDOAndPayProductDOList = payQueryService.getPayDOAndPayProductDOList(payProductDto);
		
		return payDOAndPayProductDOList;
	}
	
	@Override
	public boolean queryAv(FlightOrderDto flightOrderDto) {
		boolean flag = false;
		List<FlightInfoDto> result = null;
		//非必要参数，可不填
		String airLineCode = "";
		String groupIndicator = "";
		boolean isTaxFee = false;
		String productTP = "";
		/*//classCode取去程第一段的子仓
		String classCode = getClassCode(flightOrderDto);
		//封装fI参数  航班信息基本参数
		List<FlightItem> fI = getFlightItemList(flightOrderDto);*/
		//封装参数
		String channelCode = flightOrderDto.getChannel();
		int adtCount = 0;
		int chdCount = 0;
		int iftCount = 0;
		List<PaxDto> paxs = flightOrderDto.getPaxs();
		for (PaxDto paxDto : paxs) {
			if("ADT".equals(paxDto.getPassengerTp())){
				adtCount+=1;
			}else if("CHD".equals(paxDto.getPassengerTp())){
				chdCount+=1;
			}else{
				iftCount+=1;
			}
		}
		List<SegmentDto> segments = flightOrderDto.getPaxs().get(0).getSegments();
		outer:	for (SegmentDto segmentDto : segments) {
					String classCode = null;
						classCode = segmentDto.getClassTp();
						List<FlightItem> fI = new ArrayList<FlightItem>();
						FlightItem flightItem = new FlightItem();
						flightItem.setArrCode(segmentDto.getArrAirpCd());
						flightItem.setDepCode(segmentDto.getDepAirpCd());
						flightItem.setDepDate(new SimpleDateFormat("yyyy-MM-dd").format(segmentDto.getDepDt()));
						flightItem.setIndex(1);
						fI.add(flightItem);
						try {
							result = flightCollectServiceImpl.queryAVWithFareResult(fI, airLineCode, groupIndicator, channelCode, "OW", adtCount, chdCount, iftCount, isTaxFee, classCode, productTP);
						} catch (Exception e) {
							log.info("调用服务层查询av方法出错------"+e.getMessage());
							throw new ActionException(GlobalExceptionConstants.PAYMENT_00011);
						}
						boolean validatePriceAndCabin = validatePriceAndCabin(segmentDto, result);
						if(validatePriceAndCabin){
							flag = true;
						}else{
							flag = false;
							break outer;
						}
				}
		if(flag){
			return true;
		}else{
			return false;
		}
	}
	
	private boolean validatePriceAndCabin(SegmentDto segmentDto,
			List<FlightInfoDto> result) {
		boolean flag = false;
		for (FlightInfoDto flightInfoDto : result) {
			if(flightInfoDto.getFlightNo().equals(segmentDto.getFlightNo())){
				List<CabinInfoDto> cabins = flightInfoDto.getCabins();
				for (CabinInfoDto cabinInfoDto : cabins) {
					if(cabinInfoDto.getCabinCode().equals(segmentDto.getClassTp())){
						flag = true;
					}
				}
			}
		}
		if(flag){
			return true;
		}else{
			return false;
		}
	}

//	@Override
//	public CommonCardInfoRespDto queryCard(String scCode, String subScCode, String ceairMember) {
//		CommonCardInfoRespDto commonCardInfoRespDto = new CommonCardInfoRespDto();
//		commonCardInfoRespDto.setRspCode("01");
//		try {
//			log.info("dubbo获取常用卡信息开始");
//			commonCardInfoRespDto = commonCardInfoService.queryCardList(scCode, subScCode, ceairMember);
//			List<CommonCardNoDto> cardList = commonCardInfoRespDto.getCardList();
//			if(cardList!=null && cardList.size()>0){
//				commonCardInfoRespDto = commonCardInfoService.queryCardOne(scCode, subScCode, ceairMember, cardList.get(0).getCardSeq());
//			}
//		} catch (Exception e) {
//			log.error("dubbo获取常用卡信息错误",e);
//		}
//		return commonCardInfoRespDto;
//	}
	
//	@Override
//	public CommonCardInfoRespDto queryCardList(String scCode, String subScCode, String ceairMember) {
//		CommonCardInfoRespDto commonCardInfoRespDto = new CommonCardInfoRespDto();
//		commonCardInfoRespDto.setRspCode("01");
//		try {
//			log.info("dubbo获取常用卡信息列表开始");
//			commonCardInfoRespDto = commonCardInfoService.queryCardList(scCode, subScCode, ceairMember);
//			List<CommonCardNoDto> cardList = commonCardInfoRespDto.getCardList();
//			List<String> rspMsgs = new ArrayList<String>();
//			if(cardList!=null && cardList.size()>0){
//				for (CommonCardNoDto commonCardNoDto : cardList) {
//					CommonCardInfoRespDto commonCardInfoRespDto2 = commonCardInfoService.queryCardOne(scCode, subScCode, ceairMember, commonCardNoDto.getCardSeq());
//					rspMsgs.add(commonCardInfoRespDto2.getRspMsg());
//				}
//			}
//			if(rspMsgs!=null && rspMsgs.size()>=1){
//				commonCardInfoRespDto.setRspMsg(rspMsgs.get(0));
//				commonCardInfoRespDto.setRspMsgs(rspMsgs);				
//			}
//		} catch (Exception e) {
//			log.error("dubbo获取常用卡信息列表错误",e);
//		}
//		return commonCardInfoRespDto;
//	}

//	@Override
//	public CommonCardInfoRespDto insertCard(String scCode, String subScCode, String pcCode, String subPcCode,
//			 CardInfoDto cardInfo) {
//		CommonCardInfoRespDto commonCardInfoRespDto = new CommonCardInfoRespDto();
//		commonCardInfoRespDto.setRspCode("01");
//		try {
//			log.info("dubbo保存常用卡信息开始");
//			CommonCardInfoDto cardInfoVo = new CommonCardInfoDto();
//			cardInfoVo.setCeairMember(cardInfo.getCeairMember());
//			cardInfoVo.setCardNo(cardInfo.getCardNo());
//			cardInfoVo.setIdType(cardInfo.getIdType()==null?"":cardInfo.getIdType());
//			cardInfoVo.setIdenNo(cardInfo.getIdNo()==null?"":cardInfo.getIdNo());
//			cardInfoVo.setFullName(cardInfo.getName());
//			cardInfoVo.setFirstName(cardInfo.getCardholderName());
//			cardInfoVo.setLastName(cardInfo.getCardholderSurname());
//			cardInfoVo.setMobilePhone("");
//			cardInfoVo.setBankCode("");
//			cardInfoVo.setIssuingBank("");
//			cardInfoVo.setIssuingCountry("");
//			cardInfoVo.setBillCountry(cardInfo.getCountry()==null?"":cardInfo.getCountry());
//			cardInfoVo.setBillProvince(cardInfo.getState()==null?"":cardInfo.getState());
//			cardInfoVo.setBillCity(cardInfo.getCity()==null?"":cardInfo.getCity());
//			cardInfoVo.setBillStreet(cardInfo.getStreetName()==null?"":cardInfo.getStreetName());
//			cardInfoVo.setBillPostalCode(cardInfo.getZipCode()==null?"":cardInfo.getZipCode());
//			cardInfoVo.setBillEmail(cardInfo.getEmail()==null?"":cardInfo.getEmail());
//			cardInfoVo.setPhoneNumber(cardInfo.getBuyerPhone()==null?"":cardInfo.getBuyerPhone());
//			cardInfoVo.setCardType("");
//			cardInfoVo.setCardBin("");
//			cardInfoVo.setCardExpiration("20"+cardInfo.getValidDate().substring(2)+cardInfo.getValidDate().substring(0,2));
//			commonCardInfoRespDto  = commonCardInfoService.insertCard(scCode, subScCode, pcCode, subPcCode, cardInfoVo);		
//			
//		} catch (Exception e) {
//			log.error("dubbo保存常用卡信息错误",e);
//		}
//		return commonCardInfoRespDto;
//	}

//	@Override
//	public CommonCardInfoRespDto deleteCard(String scCode, String subScCode, CardInfoDto cardInfo) {
//		CommonCardInfoRespDto commonCardInfoRespDto = new CommonCardInfoRespDto();
//		commonCardInfoRespDto.setRspCode("01");
//		try {
//			log.info("dubbo删除常用卡信息开始");
//			commonCardInfoRespDto = commonCardInfoService.queryCardList(scCode, subScCode, cardInfo.getCeairMember());
//			List<CommonCardNoDto> cardList = commonCardInfoRespDto.getCardList();
//			if(cardList!=null && cardList.size()>0){
//				for (Iterator<CommonCardNoDto> iterator = cardList.iterator(); iterator.hasNext();) {
//					CommonCardNoDto commonCardNoDto = (CommonCardNoDto) iterator.next();
//					CommonCardInfoDto cardInfoVo = new CommonCardInfoDto();
//					cardInfoVo.setCeairMember(cardInfo.getCeairMember());
//					cardInfoVo.setCardId(commonCardNoDto.getCardSeq());
//					commonCardInfoRespDto  = commonCardInfoService.deleteCard(scCode, subScCode, cardInfoVo);
//				}
//			}
//			
//		} catch (Exception e) {
//			log.error("dubbo删除常用卡信息错误",e);
//		}
//		return commonCardInfoRespDto;
//	}

	@Override
	public List<Map<String, Object>> suspendAndResume(String orderNo,
			boolean suspend) {
		List<Map<String,Object>> ticketSuspendAndResume = ticketService.doTicketSuspendAndResume(orderNo, suspend);
		return ticketSuspendAndResume;
	}


}
